
package com.ynny.chapter04.common;

import com.ynny.chapter04.exception.UserNotAdminException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        HashMap<Object, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return R.error(420, "参数校验异常：" + map);
    }


    @ExceptionHandler(UserNotAdminException.class)
    public R handleUserNotAdminException(UserNotAdminException e) {

        return R.error(401, e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {

        return R.error(500, e.getMessage());
    }

}
